package org.wpahs.ahn.rssfeed;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import org.wpahs.ahn.rssfeed.DB.DBMyFeed;

/**
 * Created by dgambone on 01/13/2015.
 */
public class RSSAlarmReceiver extends BroadcastReceiver {

    private RSSGetService mService;
    private Boolean mServiceBound = false;
    private Context mContext = null;

    @Override
    public void onReceive(Context context, Intent intent) {
        //start the service.  And update the feeds
        mContext = context;

        if(getAutoPoll()) {
            Log.i("RSSAlarmReceiver", "onReceive");
            Intent svcIntent = new Intent(context, RSSGetService.class);


            if (!RSSAlarmReceiver.isMyServiceRunning(context, RSSGetService.class)) {
                Log.i("RSSAlarmReceiver", "Not running");
                GoGetFeeds(context);
            } else {
                Log.i("RSSAlarmReceiver", "Already Running");
                GoGetFeeds(context);
            }
        }

    }

    public static boolean isMyServiceRunning(Context context,Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }

    private boolean getAutoPoll(){
        SharedPreferences prefs=
                mContext.getSharedPreferences(
                mContext.getString(
                        R.string.preferences_gambonereader),
                        Context.MODE_PRIVATE);
        return prefs.getBoolean(
                mContext.getString(R.string.preferences_enableAuto),
                false);

    }


    private void GoGetFeeds(Context context){
            Intent i = new Intent(context, RSSGetService.class);

            i.putExtra(context.getString(R.string.URL),"");
            i.putExtra(context.getString(R.string.feed_id),0);
            context.startService(i);

    }


}
